package cn.tiga.pet.service.impl;

import cn.tiga.pet.domain.PetType;
import cn.tiga.pet.mapper.PetTypeMapper;
import cn.tiga.pet.service.IPetTypeService;
import cn.tiga.basic.service.impl.BaseServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author pping
 * @since 2022-08-06
 */
@Service
public class PetTypeServiceImpl extends BaseServiceImpl<PetType> implements IPetTypeService {
    @Autowired
    private PetTypeMapper petTypeMapper;


    @Override
    public List<PetType> typeTree() {
        // 查询这个的全部
        List<PetType> petTypes = petTypeMapper.loadAll();
        // 创建一个新集合装入id
        Map<Long, PetType> allMap = petTypes.stream().collect(Collectors.toMap(PetType::getId, item -> item));
        // 遍历获取到的每个数据 获取ID判断它是否为空
        List<PetType> types = new ArrayList<>();
        for (PetType petType : petTypes) {
            if (petType.getPid() == null) {
                types.add(petType);
            } else {
                PetType petType1 = allMap.get(petType.getPid());
                if (petType1 != null) {
                    petType1.getChildren().add(petType);
                }
            }
        }

        return types;
    }
}
